package com.wjsh.common.base.mvp;

import org.simple.eventbus.EventBus;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by chenbaolin on 2017/8/10.
 */

public class BasePresenter<M extends IModel, V extends IView> implements IPresenter {
    protected final String TAG = this.getClass().getSimpleName();

    protected CompositeDisposable mCompositeDisposable;
    protected M mModel;
    protected V mRootView;

    public BasePresenter(M mModel, V mRootView) {
        this.mModel = mModel;
        this.mRootView = mRootView;
        onStart();
    }

    public BasePresenter(V mRootView) {
        this.mRootView = mRootView;
        onStart();
    }

    public BasePresenter() {
        onStart();
    }

    @Override
    public void onStart() {
        if (useEventBus()) //如果要使用eventBus请将此方法返回true
            EventBus.getDefault().register(this);//注册EventBus
    }


    @Override
    public void onDestroy() {
        if (useEventBus())
            EventBus.getDefault().unregister(this);
        unDispose();
        if (mModel != null) mModel.onDestroy();
        this.mModel = null;
        this.mRootView = null;
        this.mCompositeDisposable = null;

    }

    protected void addDispose(Disposable disposable) {
        if (mCompositeDisposable == null)
            mCompositeDisposable = new CompositeDisposable();
        mCompositeDisposable.add(disposable);
    }

    protected void unDispose() {
        if (mCompositeDisposable != null)
            mCompositeDisposable.clear();
    }


    /**
     * 是否使用eventBus,默认为使用(true)，
     *
     * @return true
     */
    protected boolean useEventBus() {
        return true;
    }
}
